﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Service;
using MODEL;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using System.ComponentModel;
using Common;
using Microsoft.Practices.ServiceLocation;
using GalaSoft.MvvmLight.Views;
using System.Drawing;
using System.IO;

namespace ViewModel.PictureInfo
{
    public class UploadAreaWeatherPictureViewModel:ViewModelBase
    {
        public ViewModelBase ParentViewModel { get; set; }

        public ICommand UploadPictureCommand { get; set; }

        private Image m_WeatherPicture;
        public Image WeatherPicture
        {
            get { return this.m_WeatherPicture; }
            set { this.m_WeatherPicture = value; base.RaisePropertyChanged(() => this.WeatherPicture); }
        }

        private readonly Town m_NonSelectTown = new Town { TownName = "未选中乡镇" };
        private Town m_CurrentTown;
        public Town CurrentTown
        {
            get { return this.m_CurrentTown; }
            set { this.m_CurrentTown = value; base.RaisePropertyChanged(() => CurrentTown); }
        }
        private List<Town> m_TownList;
        public List<Town> TownList
        {
            get { return this.m_TownList; }
            set { this.m_TownList = value; base.RaisePropertyChanged(() => TownList); }
        }

        private AreaWeatherPicture m_AreaWeatherPicture = new AreaWeatherPicture();
        public AreaWeatherPicture AreaWeatherPicture
        {
            get { return this.m_AreaWeatherPicture; }
            set { this.m_AreaWeatherPicture = value; base.RaisePropertyChanged(() => AreaWeatherPicture); }
        }
        

        private string m_LocalImagePath;
        public string LocalImagePath
        {
            get { return this.m_LocalImagePath; }
            set { this.m_LocalImagePath = value; base.RaisePropertyChanged(() => LocalImagePath); }
        }

        private Dictionary<int, string> m_AirQuantityDict;
        public Dictionary<int, string> AirQuantityDict
        {
            get { return this.m_AirQuantityDict; }
            set { this.m_AirQuantityDict = value; base.RaisePropertyChanged(() => this.AirQuantityDict); }
        }

        private IPictureInfoService m_PictureInfoService;
        private IAreaService m_AreaService;

        public UploadAreaWeatherPictureViewModel(IPictureInfoService pictureInfoService, IAreaService areaService)
        {
            this.m_PictureInfoService = pictureInfoService;
            this.m_AreaService = areaService;

            this.UploadPictureCommand = new RelayCommand(UploadWeatherPicture);

            this.AirQuantityDict = EnumHelper.ConvertEnumToDictionary(typeof(AirQuantityEnum));
            RefreshData(() => this.PropertyChanged += OnPropertyChange);
        }

        public void OnPropertyChange(object sender, PropertyChangedEventArgs e)
        {

            if (e.PropertyName == "AreaWeatherPicture")
            {
                this.CurrentTown = this.TownList.FirstOrDefault(town => town.TownId == this.AreaWeatherPicture.Town.TownId) ?? this.m_NonSelectTown;
                this.LocalImagePath = this.AreaWeatherPicture.PictureURL;
            }
        }

        public async void RefreshData(Action afterAction = null)
        {
            try
            {
                List<Town> towns = new List<Town>() { this.m_NonSelectTown };
                towns.AddRange(await m_AreaService.GetTownList());
                this.TownList = towns;

                this.m_CurrentTown = this.m_NonSelectTown;

                if (afterAction != null)
                {
                    afterAction.Invoke();
                }
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError("加载数据失败", "错误", "确定", null);
                Log.WriteException(ex);
            }
        }

        private async void UploadWeatherPicture()
        {
            if (this.CurrentTown == null || this.CurrentTown == this.m_NonSelectTown)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("必须选择一个乡镇", "校验失败");
                return;
            }

            if (string.IsNullOrWhiteSpace(this.AreaWeatherPicture.Weather))
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("天气不能为空", "校验失败");
                return;
            }
           
            this.AreaWeatherPicture.Town = this.CurrentTown;
            try
            {
                Task task = this.m_PictureInfoService.UploadWeatherPicture(this.AreaWeatherPicture, this.LocalImagePath);
                task.Wait();

                await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("图片信息上传成功", "成功")
                    .ContinueWith(t=> {
                        this.MessengerInstance.Send<object>(null, "AreaWeatherUpload_CloseForm");
                        (this.ParentViewModel as AreaWeatherPictureViewModel)?.RefreshData();
                    });
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError($"图片上传失败:{ex.Message}", "错误", "确定", null);
            }
        }      
    }
}
